<template>
  <section class="todoapp">
    <TodoHeader @addTodo="addTodo"></TodoHeader>
    <TodoMain
      :todoList="filterList"
      :isAllDone="isAllDone"
      @delTodo="delTodo"
      @changeTodoStatus="changeTodoStatus"
      @changeAllChecked="changeAllChecked"
      @changeIsEdit="changeIsEdit"
      @endEdit="endEdit"
    ></TodoMain>
    <TodoFooter
      :todoList="filterList"
      :unDoneNumer="unDoneNumer"
      :visibility="visibility"
      @changevisibility="changevisibility"
      @delAllDone="delAllDone"
    ></TodoFooter>
  </section>
</template>

<script setup>
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";
import useLocalStoage from "./hooks/useLocalStoage";

import { ref, reactive, computed, watch } from "vue";

let todoListData = useLocalStoage("todoList").value || [];
let todoList = reactive(todoListData);

let visibility = ref("all");

// 删除todo
let delTodo = (idx) => {
  todoList.splice(idx, 1);
};

// 改变单个todo的状态
let changeTodoStatus = (idx, flag) => {
  todoList[idx].done = flag;
};

// 统计是否都已完成
let isAllDone = computed(() => {
  return todoList.every((item) => item.done === true);
});
// 点击全选或全不选
let changeAllChecked = (flag) => {
  todoList.forEach((item) => {
    item.done = flag;
  });
};
// 双击编辑
let changeIsEdit = (idx) => {
  todoList[idx].isEdit = true;
};
// 结束编辑
let endEdit = (idx, newText) => {
  todoList[idx].text = newText.trim();
  todoList[idx].isEdit = false;
};
// 添加todo
let addTodo = (text) => {
  todoList.push({
    id: Date.now(),
    text: text,
    done: false,
    isEdit: false,
  });
};

// 统计没有完成的todo的数量
let unDoneNumer = computed(() => {
  return todoList.filter((item) => item.done == false).length;
});

// 改变visibility
let changevisibility = (vsb) => {
  visibility.value = vsb;
};

// 根据visibility过滤出不同的todo
let filterList = computed(() => {
  if (visibility.value === "all") {
    return todoList;
  } else if (visibility.value === "active") {
    return todoList.filter((item) => item.done == false);
  } else {
    return todoList.filter((item) => item.done == true);
  }
});
// 删除已完成的todo
let delAllDone = () => {
  let res = todoList.filter((item) => item.done == false);
  todoList.length = 0;
  res.forEach((item) => {
    todoList.push(item);
  });
};

watch(todoList, (newTodoList) => {
  useLocalStoage("todoList", newTodoList);
});
</script>

